package com.knightboy.smartshoes.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.knightboy.smartshoes.R;
import com.knightboy.smartshoes.core.SenserData;
import com.knightboy.smartshoes.core.SharedData;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by 29288 on 2015/9/17.
 */
public class MainActivity extends FragmentActivity implements View.OnClickListener {
    private int mRecvDataCount;
    private final String ACTION_DATA_UPDATE = "com.knightBoy.dataUpdate";
    // Array adapter for the conversation thread
    private ArrayAdapter<String> mConversationArrayAdapter;
    //BLE设备的地址，名称
    final String mDeviceAddress = "78:A5:04:63:CF:19";
    //BlueToothLeService服务对象
    private static BlueToothLeService mBluetoothLeService;
    //定义布局对象,可用用来改变布局背景之类的
    private RelativeLayout menu_step_rl, menu_weight_rl, menu_data_rl, menu_navi_rl, menu_community_rl;
    //id数组，为了将来操作方便
    private final int[] bottomBarId = new int[]{R.id.rl_step,R.id.rl_weight,R.id.rl_data,R.id.rl_navi,R.id.rl_community};
    //表示初始化操作的参数
    private final int DEFAULT_OPER = 0;
    //上下文对象
    private Context context;
    //Fragment对象，不要每次都重新创建，不然每次都刷新
    private Fragment StepFrament, WeightFragment, DataFragment, NaviFragment, CommunityFragment;
    //提醒休息弹出框
    private AlertDialog breakdialog;
    //摔倒弹出框
    private AlertDialog dialog;
    //摔倒弹出框标志
    private static boolean isFallDialogOpen = false;
    //日程安排弹出菜单栏
    private PopupWindow mPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //保存上下文对象
        context = this;
        //获得控件引用
        findView();
        //给菜单图标绑定监听器
        initListener();
        //默认选中消息菜单,这里传入一个0参数,进入switch的default选项
        replaceFragmentByClick(DEFAULT_OPER);

        //蓝牙部分
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_main);
        Intent gattServiceIntent = new Intent(this, BlueToothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

        //设置摔倒与休息的handler类
        SenserData.setFallOrBreakHandler(fallOrBreakHandler);

        //日程一次提醒
        //alarmPlans();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册广播，接收service中启动的线程发送过来的信息，同时更新UI
        IntentFilter filter = makeGattUpdateIntentFilter();
        this.registerReceiver(mGattUpdateReceiver, filter);

        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
        }else{
            //Toast.makeText(FirstActivity.this,"服务不存在",Toast.LENGTH_SHORT).show();
        }

        //注册监听rssi的广播
        IntentFilter rssifilter = new IntentFilter();
        rssifilter.addAction("com.knightboy.rssi");
        this.registerReceiver(new MyBroadCaseReceiver(), rssifilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.exit(0);
    }

    private void findView(){
        menu_step_rl = (RelativeLayout)findViewById(R.id.rl_step);
        menu_weight_rl = (RelativeLayout)findViewById(R.id.rl_weight);
        menu_data_rl = (RelativeLayout)findViewById(R.id.rl_data);
        menu_navi_rl = (RelativeLayout)findViewById(R.id.rl_navi);
        menu_community_rl = (RelativeLayout)findViewById(R.id.rl_community);
        //获得fragment
        StepFrament = getSupportFragmentManager().findFragmentById(R.id.fragment_step);
        WeightFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_weight);
        DataFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_data);
        NaviFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_navi);
        CommunityFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_community);
    }

    private void initListener(){
        menu_step_rl.setOnClickListener(this);
        menu_weight_rl.setOnClickListener(this);
        menu_data_rl.setOnClickListener(this);
        menu_navi_rl.setOnClickListener(this);
        menu_community_rl.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        replaceFragmentByClick(v.getId());
    }

    //根据点击的菜单的id改变fragment
    private void replaceFragmentByClick(int id){
        //根据新的fragment替换之前的
        // 得到Fragment事务管理器
        FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
        switch (id){
            case R.id.rl_step:
                ft.hide(WeightFragment).hide(DataFragment).hide(NaviFragment).hide(CommunityFragment).show(StepFrament).commit();
                break;
            case R.id.rl_weight:
                ft.hide(StepFrament).hide(DataFragment).hide(NaviFragment).hide(CommunityFragment).show(WeightFragment).commit();
                break;
            case R.id.rl_data:
                ft.hide(StepFrament).hide(WeightFragment).hide(NaviFragment).hide(CommunityFragment).show(DataFragment).commit();
                break;
            case R.id.rl_navi:
                ft.hide(StepFrament).hide(WeightFragment).hide(DataFragment).hide(CommunityFragment).show(NaviFragment).commit();
                break;
            case R.id.rl_community:
                ft.hide(StepFrament).hide(WeightFragment).hide(NaviFragment).hide(DataFragment).show(CommunityFragment).commit();
                break;
            default:
                ft.hide(DataFragment).hide(WeightFragment).hide(NaviFragment).hide(CommunityFragment).show(StepFrament).commit();
                //设置默认选中菜单的图片及字体颜色
                ImageView iv_message_default = (ImageView)findViewById(R.id.iv_step);
                TextView tv_message_default = (TextView)findViewById(R.id.tv_step);
                iv_message_default.setSelected(true);
                tv_message_default.setTextColor(getResources().getColor(R.color.menu_text_click));
                break;
        }

        //改变按钮的样式，在不是初始化操作的时候
        if(id != DEFAULT_OPER){
            for(int i = 0; i < 5; i++){
                //获取到菜单的RelativeLayout
                RelativeLayout barLayout = (RelativeLayout)findViewById(bottomBarId[i]);
                ImageView imageView;
                TextView textView;
                //判断是不是消息菜单项
                if(barLayout.getChildAt(0) instanceof LinearLayout){
                    LinearLayout linearLayout = (LinearLayout)barLayout.getChildAt(0);
                    imageView = (ImageView)linearLayout.getChildAt(0);
                    textView = (TextView)linearLayout.getChildAt(1);
                }else{
                    FrameLayout frameLayout = (FrameLayout)barLayout.getChildAt(0);
                    LinearLayout linearLayout = (LinearLayout)frameLayout.getChildAt(0);
                    imageView = (ImageView)linearLayout.getChildAt(0);
                    textView = (TextView)linearLayout.getChildAt(1);
                }
                //设置图片的状态
                if(id == bottomBarId[i]){
                    imageView.setSelected(true);
                    textView.setTextColor(getResources().getColor(R.color.menu_text_click));
                }else {
                    imageView.setSelected(false);
                    textView.setTextColor(getResources().getColor(R.color.menu_text_normal));
                }
            }
        }
    }

    //***************蓝牙部分************************************************************************
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BlueToothLeService.LocalBinder) service).getService();
            if(mBluetoothLeService == null){
            }
            if (!mBluetoothLeService.initialize()) {
                finish();
            }
            // Automatically connects to the device upon successful start-up
            // initialization.
            mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    // 处理来自BlueToothLeService发送的广播
    // ACTION_GATT_CONNECTED: 连接上GATT服务器
    // ACTION_GATT_DISCONNECTED: 与GATT服务器断开
    // ACTION_GATT_SERVICES_DISCOVERED: 发现GATT服务器
    // ACTION_DATA_AVAILABLE: 从设备上读到数据，可能是直接读取了或者更新操作
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BlueToothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                updateConnectionState(R.string.connected);
                invalidateOptionsMenu();
                mRecvDataCount = 0;
            } else if (BlueToothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                updateConnectionState(R.string.disconnected);
                invalidateOptionsMenu();
                clearUI();
            }
            //收到了读取到数据的广播后广播接收器执行的操作
            else if (BlueToothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                //读取Rssi数值
                mBluetoothLeService.readRemoteRssi();

                //获得数据,getRecvedData()是同步操作的
                ArrayList<byte[]> arrayList = mBluetoothLeService.getRecvedData();
                int i = 0;
                while ((i++<10) && (arrayList.size() > 0)) {
                    //获得数据队列第一项
                    byte[] data = arrayList.remove(0);

                    //获得20字节的数据项
                    if (data != null && data.length >= 20) {
                        //检查第一个字节和最后一个字节,符合要求就是需要的数据
                        if(data[0] == 83 && data[19] == 90){
                            try{
                                SenserData.handleByteArray(data);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }else if(data[0] == 84 && data[11] == 90){
                            SenserData.handleByteArray(data, true);
                        }
                        mRecvDataCount += data.length;
                        //发出更新界面的广播
                        sendBroadcast(new Intent(ACTION_DATA_UPDATE));
                    }
                }
            }
        }
    };

    private void clearUI() {
        mConversationArrayAdapter.clear();
    }

    /**
     * 更新界面的连接状态
     * @param resourceId
     */
    private void updateConnectionState(final int resourceId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    /**
     * 向蓝牙发送数据
     * @param command 要发送的数据，数字字符串
     */
    public static void sendMessage(int command) {
        // 检查是否真的建立了连接
        if (mBluetoothLeService.getState() != BlueToothLeService.STATE_CONNECTED) {
            //Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        //根据对应命令生成16进制命令
        byte[] data = new byte[]{0x00};
        switch (command){
            case 0:
                data = new byte[]{0x00};
                break;
            case 1:
                data = new byte[]{0x01};
                break;
            case 2:
                data = new byte[]{0x02};
                break;
            case 3:
                data = new byte[]{0x03};
                break;
            case 4:
                data = new byte[]{0x04};
                break;
            default:
                break;
        }
        //发送16进制的命令
        mBluetoothLeService.write(data);
    }

    /**
     * 生成接收蓝牙数据更新广播的IntentFilter对象
     * @return
     */
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BlueToothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BlueToothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BlueToothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BlueToothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    /**
     * 广播接收器类
     */
    class MyBroadCaseReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent intent) {
            final String rssiAction = "com.knightboy.rssi";
            final String action = intent.getAction();
            //根据动作分辨是rssi的广播还是室外导航的广播
            if (rssiAction.equals(action)){
                //手机被盗,手机，鞋垫发生震动
                Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                vibrator.vibrate(2000);
                startAlarm();
                sendMessage(5);
            }
        }
    }
    //****************蓝牙部分结束****************************************************************************

    //***********************************Handler*****************************
    /**
     * 摔倒报警,提醒休息Handler类
     */
    Handler fallOrBreakHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.arg1 == 1){
                if(isFallDialogOpen == false){
                    isFallDialogOpen = true;
                    dialog = new AlertDialog.Builder(context).setTitle("你摔倒了吗？")//.setIcon(R.drawable.fall)
                            .setPositiveButton("是的", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startAlarm();
                                    dialog.dismiss();
                                    isFallDialogOpen = false;
                                }
                            }).setNegativeButton("不是",new DialogInterface.OnClickListener(){
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    isFallDialogOpen = false;
                                    SenserData.setIsfallen(false);
                                }
                            }).create();
                    dialog.show();

                    //创建定时器,五秒后结报警
                    Timer timer = new Timer();
                    //创建定时任务
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            if(SenserData.getIsFallen() == true){
                                startAlarm();
                                dialog.dismiss();
                                isFallDialogOpen = false;
                            }
                        }
                    };
                    //定时任务启动
                    timer.schedule(task, 5000);
                }
            }else if(msg.arg1 == 2){
                //提醒用户及时去活动一下
                //创建对话框
                LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.view_breaktime_dialog, null);
                AlertDialog.Builder ad =new AlertDialog.Builder(context);
                ad.setView(view);
                ad.setTitle("待久了，出去活动一下吧！");
                breakdialog =ad.create();
                breakdialog.setButton("现在就去", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        breakdialog.cancel();
                        SharedData.setLastStepTime();
                        SenserData.setHasAwake(false);
                    }
                });
                breakdialog.setButton2("下次提醒", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        breakdialog.cancel();
                        SharedData.setLastStepTime();
                        SenserData.setHasAwake(false);
                    }
                });
                breakdialog.show();
            }
        }
    };
    //*********************************Handler定义结束*****************************

    //********************************播放系统铃声*********************************

    /**
     * 播放报警音乐
     */
    private void startAlarm() {
        MediaPlayer mMediaPlayer = MediaPlayer.create(this, getSystemDefultRingtoneUri());
        mMediaPlayer.setLooping(false); //不循环，只播放一遍
        try {
            mMediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMediaPlayer.start();
    }

    //获取系统默认铃声的Uri
    private Uri getSystemDefultRingtoneUri() {
        return RingtoneManager.getActualDefaultRingtoneUri(this,
                RingtoneManager.TYPE_RINGTONE);
    }

    //********************************播放系统铃声段结束****************************

    //********************************伪日程提醒***********************************

    /**
     * 设置定时的日程提醒
     */
    private void alarmPlans(){
        //创建定时器,一秒后结束震动
        Timer timer = new Timer();
        //创建定时任务
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0);
            }
        };
        //定时任务启动
        timer.schedule(task, 1000*10);
    }

    /**
     * 要转为在主线程更新ui
     */
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                getPopupWindowInstance();
                mPopupWindow.showAtLocation(menu_step_rl, Gravity.CENTER, 0, 0);
                backgroundAlpha(0.3f);
            }
        }
    };

    /*
     * 获取PopupWindow实例
     */
    private void getPopupWindowInstance() {
        if (null != mPopupWindow) {
            mPopupWindow.dismiss();
            return;
        } else {
            initPopuptWindow();
        }
    }

    /*
     * 创建PopupWindow
     */
    private void initPopuptWindow() {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View popupWindow = layoutInflater.inflate(R.layout.view_popupwindow, null);

        // 创建一个PopupWindow
        // 参数1：contentView 指定PopupWindow的内容
        // 参数2：width 指定PopupWindow的width
        // 参数3：height 指定PopupWindow的height
        mPopupWindow = new PopupWindow(popupWindow, 600, 600, true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //恢复背景透明度
                backgroundAlpha(1f);
            }
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    //****************************************伪日程提醒结束*****************************
}
